A variable in JavaScript can contain any data. A variable can at one moment be a string and later receive a numeric value:
// no error let message = "hello"; message = 123456;
在程式語言中,所謂的 “dynamically typed”, 指的是雖然有type
但是變數不會侷限於某個type
.
let n = 123; n = 12.345;
四則運算:加減乘除
特殊值: Infinity
, -Infinity
and NaN
.
Infinity
也就是 ∞. 大於任意數字。
可以由除0得到。
alert( 1 / 0 ); // Infinity
或者
javascript alert( Infinity ); // Infinity
NaN
代表計算錯誤。例如
alert( "not a number" / 2 ); // NaN, such division is erroneous
NaN
:任意數字和她運算,都是 NaN
:
alert( "not a number" / 2 + 5 ); // NaN
So, if there’s NaN
somewhere in a mathematical expression, it propagates to the whole result.
三種方式表示雙引號:
"Hello"
.'Hello'
.`Hello`
.let str = "Hello"; let str2 = 'Single quotes are ok too'; let phrase = `can embed ${str}`;
in ${…}
, for example:
let name = "John"; // embed a variable alert( `Hello, ${name}!` ); // Hello, John! // embed an expression alert( `the result is ${1 + 2}` ); // the result is 3
echo off set x="xxx" echo %x%
錯誤: 因為雙引號不作用
alert( "the result is ${1 + 2}" ); // the result is ${1 + 2} (double quotes do nothing)
沒有 character 型態。
例如,C, java 有形態 char
但是JavaScript沒有。只有string
.。
兩個值: true
and false
.
let nameFieldChecked = true; // yes, name field is checked let ageFieldChecked = false; // no, age field is not checked
Boolean values also come as a result of comparisons:
let isGreater = 4 > 1; alert( isGreater ); // true (the comparison result is "yes")
這個值null
,有它自己的型態。
let age = null;
In JavaScript null
is not a “reference to a non-existing object” or a “null pointer” like in some other languages.
“nothing”, “empty” or “value unknown”.
The code above states that the age
is unknown or empty for some reason.
undefined
也是有它自己的型態。 意思是,沒有指派值。
let x; //已經被宣告,但是沒定義 alert(x); // shows "undefined"
雖然也可以拿來指派給變數,但是沒有意義.
let x = 123; x = undefined; alert(x); // "undefined"
前面的null也是一個值,
let x=null
但是,程式人員指派這個null的意思是說,我們要確認他是空的。但是undefiend
的原本意義在讓我們知道這是空值。
more ...
typeof
也是一個運算元。
語法有兩種:
typeof x
.typeof(x)
.```javascript typeof undefined // "undefined" typeof 0 // "number" typeof true // "boolean" typeof "foo" // "string" typeof Symbol("id") // "symbol" typeof Math // "object" (1) typeof null // "object" (2) typeof alert // "function" (3)
The last three lines may need additional explanations:
Math
是一個內建的物件。moretypeof null
的運算結果 "object"
. 這個結果是錯的,這是已知的錯誤,但是為了相容性,仍然留著,這是一個值。